<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <el-row>
        <span>选择商品分类：</span>
        <el-cascader
          v-model="selectedCateKeys"
          :options="cateList"
          :props="paramsPorps"
          @change="handleChange"
        ></el-cascader>
      </el-row>
      <!-- Tab栏区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数区域 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" @click="addparams" :disabled="activeDisbled">添加参数</el-button>
          <!-- 动态参数表格区域 -->
          <el-table :data="manyList" style="width: 100%">
            <el-table-column type="expand">
              <!-- attr_vals参数 -->
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 添加的输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 显示输入框按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作" width="180px">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  class="el-icon-edit"
                  size="mini"
                  @click="editParams(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  class="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性区域 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" @click="addparams" :disabled="activeDisbled">添加属性</el-button>
          <!-- 静态参数表格区域 -->
          <el-table :data="onlyList" style="width: 100%">
            <el-table-column type="expand">
              <!-- attr_vals参数 -->
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 添加的输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 显示输入框按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作" width="180px">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  class="el-icon-edit"
                  size="mini"
                  @click="editParams(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  class="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数属性对话框 -->
      <el-dialog
        :title="'添加'+activeTitle"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="addFormClose"
      >
        <el-form ref="addFormRef" :model="addFormList" label-width="120px" :rules="addFormRules">
          <el-form-item :label="activeTitle+'名称'" prop="attr_name">
            <el-input v-model="addFormList.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParamsSub">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改参数属性对话框 -->
      <el-dialog :title="'修改'+activeTitle" :visible.sync="editDialogVisible" width="30%">
        <el-form ref="editFormRef" :model="editFormList" label-width="120px" :rules="editFormRules">
          <el-form-item :label="activeTitle+'名称'" prop="attr_name">
            <el-input v-model="editFormList.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParamsSub">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 商品分类数据
      cateList: [],
      // 级联参数
      paramsPorps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      // 级联选择框双向绑定的数据数组
      selectedCateKeys: [],
      // 动态的name名
      activeName: "many",
      // 动态参数列表
      manyList: [],
      // 静态属性列表
      onlyList: [],
      // 添加属性对话框显示
      addDialogVisible: false,
      // 添加属性名
      addFormList: {
        name: ""
      },
      addFormRules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }]
      },
      // 修改属性对话框显示
      editDialogVisible: false,
      // 修改绑定的数据
      editFormList: {},
      // 修改属性数据验证
      editFormRules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }]
      }
      // // 输入框显示
      // inputVisible: false,
      // // 输入框绑定的数据
      // inputValue: ""
    };
  },
  created() {
    this.getCateList();
  },
  computed: {
    // 当按钮需要被禁用时返回true 否则返回false
    activeDisbled() {
      if (this.selectedCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 返回选中的三级分类的id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2];
      }
      return null;
    },
    // 动态添加文本框title文本
    activeTitle() {
      if (this.activeName == "many") {
        return "动态参数";
      }
      return "静态属性";
    }
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      // console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类数据失败");
      this.cateList = res.data;
      // console.log(this.cateList);
    },
    // 获取参数列表
    async getParamsList() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = [];
        this.manyList = [];
        this.onlyList = [];
        return;
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      res.data.forEach(item => {
        // console.log(item);
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        // 控制按钮与文本框的显示与隐藏
        item.inputVisible = false;
        // 输入文本框中输入的内容
        item.inputValue = "";
      });
      if (this.activeName === "many") {
        this.manyList = res.data;
      } else {
        this.onlyList = res.data;
      }
    },
    // 级联数据改变时触发函数
    handleChange() {
      this.getParamsList();
    },
    // 切换导航栏时触发
    handleClick() {
      this.getParamsList();
      // console.log(this.activeName);
    },
    // 添加属性
    addparams() {
      this.addDialogVisible = true;
    },
    // 关闭对话框重置表单
    addFormClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击对话框确定发起请求
    addParamsSub() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addFormList.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) return this.$message.error("添加失败");
        this.getParamsList();
        this.$message.success("添加成功");
        this.addDialogVisible = false;
      });
    },
    // 修改属性
    async editParams(attr_id) {
      // 获取参数名称
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`
      );
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.editFormList = res.data;
      this.editDialogVisible = true;
    },
    // 点击提交按钮修改参数属性
    editParamsSub() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editFormList.attr_id}`,
          {
            attr_name: this.editFormList.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 200) return this.$message.error("更新失败");
        this.editDialogVisible = false;
        this.$message.success("更新成功");
        this.getParamsList();
      });
    },
    // 删除属性功能
    async deleteParams(attr_id) {
      const a = await this.$confirm(
        "此操作将永久删除该属性, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (a === "confirm") {
        const { data: res } = await this.$http.delete(
          `categories/${this.cateId}/attributes/${attr_id}`
        );
        if (res.meta.status !== 200) return this.$message.error("删除参数失败");
        this.$message.success("删除成功");
        this.getParamsList();
      }
    },
    // 添加输入框失去焦点,点击回车触发的函数
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      let inputValue = row.inputValue;
      if (inputValue) {
        row.attr_vals.push(row.inputValue.trim());
      }
      row.inputVisible = false;
      row.inputValue = "";
      this.saveInput(row);
    },
    // 获取参数项
    async saveInput(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(",")
        }
      );
      if (res.meta.status !== 200) return this.$message.error("更新失败");
      this.$message.success("更新成功");
    },
    // 删除对应的tags
    handleClose(i, row) {
      row.attr_vals.splice(i, 1);
      this.saveInput(row);
    },
    // 点击按钮显示输入框
    showInput(row) {
      row.inputVisible = true;
      // 输入框自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    }
  }
};
</script>
<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-input {
  width: 150px;
}
.el-tag {
  margin: 10px;
}
</style>
